package com.training.java.redbox.struts.web;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.struts.domain.Customer;
import com.training.java.redbox.struts.domain.CustomerService;
import com.training.java.redbox.struts.domain.DAOException;
import com.training.java.redbox.struts.domain.OrderService;
import com.training.java.redbox.struts.domain.Orders;
import com.training.java.redbox.struts.domain.OrdersDAO;
import com.training.java.redbox.struts.domain.OrdersDAOJDBCImpl;
import com.training.java.redbox.struts.domain.ServiceException;

public class FinalCheckoutAction extends Action{
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		ServletContext servletContext = servlet.getServletContext();
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		OrderService orderService = context.getBean(OrderService.class);
		
		Customer customer = (Customer) request.getSession().getAttribute("Customer");
		List<Long> ids = (List<Long>)request.getSession().getAttribute("cart");
		//OrdersDAO orderDao = new OrdersDAOJDBCImpl();
		
		
		try{
				long orderNum = orderService.getOrderNumber();
				System.out.println("orderNum= " + orderNum);

			for (long id : ids)
			{
				Orders order = new Orders();
				
				order.setStatus("rented");
				order.setCustomer_id(customer.getCustomerId());
				order.setMovie_id(id);
				order.setOrderNumber(orderNum);
		
				orderService.createOrders(order);
				request.getSession().removeAttribute("cart");
				request.getSession().setAttribute("order", order);
				
			}
			
		} catch (ServiceException e)
			{
				e.printStackTrace();
			}
		
		return mapping.findForward("ordersummary");
	}

}
